//
//  XHRegisterViewController.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-7-17.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//
#import "AFNetworking.h"
#import "MBProgressHUD.h"

@implementation UIScrollView (UITouchEvent)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}

@end

#import "XHRegisterViewController.h"
@interface XHRegisterViewController()
{
    MBProgressHUD* HUD;
}
@property (nonatomic ,strong) UIView *registerView;
@property (nonatomic, strong ) NSMutableArray* textArray;
@property (nonatomic, strong) UIButton* registerButton;
@property (nonatomic, strong) UIButton* ptButton;
@property (nonatomic, strong) UIButton* smButton;
@property (nonatomic, strong) UIView* addView;
@property (nonatomic, strong) UIScrollView* scro;

@end


@implementation XHRegisterViewController
@synthesize name;
@synthesize username;
@synthesize phone;
@synthesize email =  _email,pwd,pwd1;
@synthesize textArray;
@synthesize registerButton;
@synthesize ptButton = _ptButton, smButton = _smButton;
@synthesize addView = _addView;
@synthesize scro  = _scro;
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.leftButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        self.leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        @weakify(self);
        [[self.leftButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }];
        self.rightButton.hidden = YES;
        NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"RegisterView" owner:self options:nil];
        _registerView = [array objectAtIndex:0];
        CGRect rect = self.view.frame;
        CGFloat oY = kIOS_VERSION<7.0?44:64;
        [_registerView setFrame:CGRectMake(0, oY, rect.size.width, rect.size.height-oY)];
        UIGestureRecognizer* tap = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(ff)];
        [_registerView addGestureRecognizer:tap];
        _registerView.userInteractionEnabled = YES;
        
        //[self.view addSubview:_registerView];
    }
    return self;
}
-(void)viewDidLoad{
     CGFloat oY = kIOS_VERSION<7.0?44:64;
    [super viewDidLoad];
    UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(70, 30+oY, 80, 25)];
    [button1 setTitle:@"普通注册" forState:UIControlStateNormal];
    [button1 setBackgroundColor:[UIColor blueColor]];
    [button1 addTarget:self action:@selector(putong) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(170, 30+oY, 80, 25)];
    [button2 setTitle:@"实名注册" forState:UIControlStateNormal];
    [button2 setBackgroundColor:[UIColor darkGrayColor]];
    [button2 addTarget:self action:@selector(shiming) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    self.ptButton = button1;
    self.smButton = button2;
    UILabel* l = [[UILabel alloc] initWithFrame:CGRectMake(20, oY+55, 280, 1)];
    l.backgroundColor = [UIColor grayColor];
    l.alpha = 0.5;
    [self.view addSubview:l];
    UIScrollView* scroV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, oY+56, 320, self.view.frame.size.height-oY-55)];
    [self.view addSubview:scroV];
    UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 80, 20)];
    l1.backgroundColor = [UIColor clearColor];
    l1.textColor = [UIColor blackColor];
    l1.text = @"用户名:";
    l1.textAlignment = NSTextAlignmentRight;
    [scroV addSubview:l1];
    UILabel* l2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 80, 20)];
    l2.backgroundColor = [UIColor clearColor];
    l2.textColor = [UIColor blackColor];
    l2.text = @"密码:";
    l2.textAlignment = NSTextAlignmentRight;
    [scroV addSubview:l2];
    UILabel* l3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 60, 80, 20)];
    l3.backgroundColor = [UIColor clearColor];
    l3.textColor = [UIColor blackColor];
    l3.text = @"确认密码:";
    l3.textAlignment = NSTextAlignmentRight;
    [scroV addSubview:l3];
    UILabel* l4 = [[UILabel alloc] initWithFrame:CGRectMake(0, 85, 80, 20)];
    l4.backgroundColor = [UIColor clearColor];
    l4.textColor = [UIColor blackColor];
    l4.text = @"姓名:";
    l4.textAlignment = NSTextAlignmentRight;
    [scroV addSubview:l4];
    UILabel* l5 = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, 80, 20)];
    l5.backgroundColor = [UIColor clearColor];
    l5.textColor = [UIColor blackColor];
    l5.text = @"手机号:";
    l5.textAlignment = NSTextAlignmentRight;
    [scroV addSubview:l5];
    UILabel* l6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 135, 80, 20)];
    l6.backgroundColor = [UIColor clearColor];
    l6.textColor = [UIColor blackColor];
    l6.text = @"邮箱:";
    l6.textAlignment = NSTextAlignmentRight;
    [scroV addSubview:l6];
    textArray = [[NSMutableArray alloc] init];;
    for (int i = 0; i < 6; i ++)
    {
        UITextField* text = [[UITextField alloc] initWithFrame:CGRectMake(90, 10+i*25, 170, 20)];
        text.borderStyle = UITextBorderStyleRoundedRect;
        text.font = [UIFont systemFontOfSize:12];
        if (i == 1 || i ==2)
        {
            text.secureTextEntry = YES;
        }
        else if (i == 4)
        {
            text.keyboardType = UIKeyboardTypeNumberPad;
        }
        [scroV addSubview:text];
        
        [textArray addObject:text];
        
    }
    UIView* addVie = [[UIView alloc] initWithFrame:CGRectMake(0, 10+6*25, 320, 80+15+20)];
    self.addView = addVie;
    UILabel* l7 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
    l7.backgroundColor = [UIColor clearColor];
    l7.textColor = [UIColor blackColor];
    l7.text = @"工作单位:";
    l7.textAlignment = NSTextAlignmentRight;
    [addVie addSubview:l7];
    UILabel* l8 = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 80, 20)];
    l8.backgroundColor = [UIColor clearColor];
    l8.textColor = [UIColor blackColor];
    l8.text = @"工作地区:";
    l8.textAlignment = NSTextAlignmentRight;
    [addVie addSubview:l8];
    
    UILabel* l9 = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 80, 20)];
    l9.backgroundColor = [UIColor clearColor];
    l9.textColor = [UIColor blackColor];
    l9.text = @"身份证:";
    l9.textAlignment = NSTextAlignmentRight;
    [addVie addSubview:l9];
    
    UILabel* l17 = [[UILabel alloc] initWithFrame:CGRectMake(0, 75, 80, 20)];
    l17.backgroundColor = [UIColor clearColor];
    l17.textColor = [UIColor blackColor];
    l17.text = @"性别:";
    l17.textAlignment = NSTextAlignmentRight;
    [addVie addSubview:l17];
    UILabel* l18 = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 80, 20)];
    l18.backgroundColor = [UIColor clearColor];
    l18.textColor = [UIColor blackColor];
    l18.text = @"所在地址:";
    l18.textAlignment = NSTextAlignmentRight;
    [addVie addSubview:l18];
    
    for (int i = 0; i < 5 ; i ++)
    {
        UITextField* text = [[UITextField alloc] initWithFrame:CGRectMake(90, i*25, 170, 20)];
        text.borderStyle = UITextBorderStyleRoundedRect;
        text.font = [UIFont systemFontOfSize:12];
        [addVie addSubview:text];
        [textArray addObject:text];
        if (i == 1)
        {
            text.text = ALLNAME;//复制时替换成 地址
            text.enabled = NO;
            //text.editing = NO;
        }
        if (i == 2)
        {
            text.keyboardType = UIKeyboardTypeNumberPad;
        }
        if (i == 3)
        {
            UIPickerView* genderPickView_ = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
            genderPickView_.dataSource = self;
            genderPickView_.delegate = self;
            text.inputView = genderPickView_;
            text.text = @"男";
        }
    }
    
    scroV.scrollEnabled = YES;
    scroV.contentSize = CGSizeMake(320, 540);
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(20, 10+25*6+10+20, 280,30)];
    [button setTitle:@"注册" forState:UIControlStateNormal];
    button.tag = 1;
    [button addTarget:self action:@selector(tijiao:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundColor:[XHRegisterViewController colorWithHexString:@"#A6C4E8"]];
    [scroV addSubview:button];
    self.registerButton = button;
    button1.selected = YES;
    self.scro = scroV;
  
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
-(void)putong
{
    if (self.ptButton.selected)
    {
        return;
    }
    self.ptButton.backgroundColor = [UIColor blueColor];
    self.smButton.backgroundColor = [UIColor darkGrayColor];
    [self.addView removeFromSuperview];
    self.smButton.selected = NO;
    self.ptButton.selected = YES;
    self.registerButton.frame = CGRectMake(20, 10+25*6+10, 280,30);
    
}
-(void)shiming
{
    if (self.smButton.selected)
    {
        return;
    }
    self.ptButton.backgroundColor = [UIColor darkGrayColor];
    self.smButton.backgroundColor = [UIColor blueColor];
    self.ptButton.selected = NO;
    self.smButton.selected = YES;
    [self.scro addSubview:self.addView];
    self.registerButton.frame = CGRectMake(20, 10+25*9+20+10+20, 280, 30);
}
-(void)ff
{
    NSLog(@"111");
    for (id item  in textArray)
    {
        [item resignFirstResponder];
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"2");
    for (id item  in textArray)
    {
        [item resignFirstResponder];
    }
    [self.name resignFirstResponder];
    [self.pwd1 resignFirstResponder];
    [self.pwd resignFirstResponder];
    [self.email resignFirstResponder];
    [self.username resignFirstResponder];
    [self.phone resignFirstResponder];
}
-(void)tijiao:(UIButton*)button
{
    
           NSLog(@"tijiao");
        [self putongzhuce];
    
}
-(void)shimingzhuce
{
    
}
-(void)putongzhuce
{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    int count = 6;
    if (self.smButton.selected)
    {
        count = 9;
    }
    for (int i = 0; i < count; i ++)
    {
        UITextField* te = textArray[i];
        [te resignFirstResponder];
        if ([te.text length] == 0)
        {
            [te becomeFirstResponder];
            UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写正确信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [view show];
            return;
            
        }
    }
    UITextField* t1 = [textArray objectAtIndex:1];
    UITextField* t2 = [textArray objectAtIndex:2];
    if (![t1.text isEqualToString:t2.text])
    {
        [t1 becomeFirstResponder];
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"密码不一致" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [view show];
        return;
    }
    UITextField* t0 = textArray[0];
    UITextField* t3 = textArray[3];
    UITextField* t4 = textArray[4];
    UITextField* t5 = textArray[5];
    if ([t4.text length] !=11)
    {
        [t4 becomeFirstResponder];
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式不对" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [view show];
        return;
    }
    if (![self validateEmail:t5.text])
    {
        [t5 becomeFirstResponder];
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"邮箱地址格式不对" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [view show];
        return;
    }
    
    
    
   // NSLog(@"dishi  =%@",_dizhistring);
    //NSDictionary* dic = @{@"code":@"149725", @"name":t0.text, @"password":t1.text, @"nickname":t3.text, @"phone":t4.text,@"email":t5.text,@"userRegIP":@"192.168.1.11",@"longitude":@"1",@"latitude":@"1"};
    NSString* st = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/regDefault.html?code=%@&name=%@&password=%@&email=%@&nickName=%@&phone=%@&userRegIP=192.168.1.1&longitude=1&latitude=2",COUTURYCODE,t0.text,t1.text,t5.text,t3.text,t4.text];
    NSLog(@"st = %@",st);//复制时替换成 县区code  需要往回传手机IP 和 经纬度，此功能没实现 ;
    if (self.smButton.selected)
    {
        UITextField* t6 = textArray[6];
        UITextField* t7 = textArray[7];
        UITextField* t8 = textArray[8];
        UITextField* t9 = textArray[9];
        NSString *personIDRegex = @"^([0-9]{14}|[0-9]{17})([0-9]|[xX])$";
        NSPredicate *personIDPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", personIDRegex];
        if (![personIDPredicate evaluateWithObject:t8.text]) {
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
          
            HUD.dimBackground = YES;
            
            HUD.labelText = @"身份证号码不正确";[self.view addSubview:HUD];
            NSLog(@"22");
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            } completionBlock:^{
                [HUD removeFromSuperview];
            }];
            return;
        }

        NSInteger gender = 1 ;
        if ([t9.text isEqualToString:@"男"])
        {
            gender = 0;
        }
        UITextField* t10 = textArray[10];
        st = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/regAuth.html?code=%@&name=%@&password=%@&email=%@&nickName=%@&phone=%@&workUnit=%@&job=%@&cardId=%@&gender=%d&userRegIP=192.168.1.11&longitude=1&latitude=2&adress=%@",COUTURYCODE,t0.text,t1.text,t5.text,t3.text,t4.text,t6.text,t7.text,t8.text,gender,t10.text]; //复制时替换成 县区code  需要往回传手机IP 和 经纬度，此功能没实现 ;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
        NSLog(@"st = %@",st);
    }
    [HUD hide:YES];
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在注册";
    HUD.dimBackground = YES;
    [self.view addSubview:HUD];
    [HUD show:YES];
    st = [st stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:st parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        [HUD hide:YES];
        NSString* string = [NSString stringWithFormat:@"%@",jsonObject[@"result"]];
        butoncl* al = [[butoncl alloc] init];
        [al postString:@"023"fff:@""];
        if ([string isEqualToString:@"success"])
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            v1.tag = 100086;
            [v1 show];
            
            // NSUserDefaults* de = [NSUserDefaults standardUserDefaults];
            // [de removeObjectForKey:@"UID"];
            // [de synchronize];
            
            NSLog(@"1222");
            //  [[NSNotificationCenter defaultCenter] postNotificationName:@"Logout1" object:nil];
            NSLog(@"2233");
        }
        else
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [v1 show];
        }
        //self.usreL.text = [jsonObject objectForKey:@"name"];
        //self.nameL.text = [jsonObject objectForKey:@"nickName"];
        //[self.ve setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://183.203.18.45:7001%@",jsonObject[@"qRcodePath"]]] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        [HUD hide:YES];
        UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"注册失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v1 show];
        NSLog(@"error11 = %@",error);
    }];
}
- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}

#pragma PickView

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}



- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return  [GENDER count];
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    UITextField* t = [textArray objectAtIndex:9];
    t.text = GENDER[row];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return GENDER[row];
    
}



@end
